//
//  SubscribeVC.m
//  Faker
//
//  Created by dllo on 15/10/28.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "ZGLSubscribeVC.h"
#import "ZGLShufflingViewCell.h"
#import "ZGLSubscribeCell.h"
#import "ZGLHTTPTOOL.h"
#import "ZGLShufflingViewModel.h"
#import "ZGLOptionsModel.h"
#import <UIImageView+AFNetworking.h>
#import "ZGLSubDetailsVC.h"
#import "ZGLSearchVC.h"
#import "ZGLChannelModel.h"
#import "ZGLSubDetModel.h"
#import "ZGLTopicTypeVC.h"
#import "ZGLTopicModel.h"
#import "ZGLTopicDetModel.h"
#import "ZGLTablePicVC.h"
#import "ZGLPicVCModel.h"
#import "ZGLPhotoVC.h"
#import "ZGLEpisodeVC.h"
#import "ZGLmyVC.h"


@interface ZGLSubscribeVC () <UITableViewDelegate, UITableViewDataSource, ZGLSubscribeCellDelegate> 

@property (nonatomic, strong) NSMutableDictionary *dic;
@property (nonatomic, strong) UITableView *subscibeTableView;
@property (nonatomic, strong) NSMutableArray *optionsArr;
@property (nonatomic, strong) NSMutableArray *imageOptionsArr;
@property (nonatomic, strong) NSMutableArray *oldArr;




@end

@implementation ZGLSubscribeVC

- (void)dealloc {
    _subscibeTableView.delegate = nil;
    _subscibeTableView.dataSource = nil;
}

- (void)handleData {
    [ZGLHTTPTOOL GETWithURL:@"http://iphone.myzaker.com/zaker/apps_v3.php?_appid=AndroidPhone&_version=6.41&m=1445400365" withBody:nil withHttpHead:nil responseStyle:JSON withSuccess:^(id result) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSArray *arr = result[@"data"][@"datas"];
        NSMutableArray *modelArr = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *dic in arr) {
            if ([dic[@"title"] isEqualToString:@"生活"]) {
                for (NSDictionary *dict in dic[@"sons"]) {
                    for (NSDictionary *dictt in dict[@"sons"]) {
                        [modelArr addObject:dictt];
                    }
                }
            }
            if ([dic[@"title"] isEqualToString:@"本地新闻"]) {
                NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
                for (NSDictionary *dict in dic[@"sons"]) {
                    for (NSDictionary *dictt in dict[@"sons"]) {
                        [modelArr addObject:dictt];
                        [arr addObject:dictt];
                    }
                }
                [user setObject:arr forKey:@"localNews"];
                [user synchronize];
            }
            if ([dic[@"title"] isEqualToString:@"微信公众号"]) {
                NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
                for (NSDictionary *dict in dic[@"sons"]) {
                    for (NSDictionary *dictt in dict[@"sons"]) {
                        [modelArr addObject:dictt];
                        [arr addObject:dictt];
                    }
                }
                [user setObject:arr forKey:@"weixin"];
                [user synchronize];
            }

            else {
                for (NSDictionary *dict in dic[@"sons"]) {
                    NSArray *soyArr = dict[@"sons"];
                    if (soyArr.count > 0) {
                        for (NSDictionary *dictt in soyArr) {
                            [modelArr addObject:dictt];
                        }
                    } else {
                        [modelArr addObject:dict];
                    }
                }
            }
        }
        NSSet *modelSet = [NSSet setWithArray:modelArr];
        modelArr = [modelSet allObjects].mutableCopy;
        if (_oldArr.count != modelArr.count) {
            [self saveNSUserDefaultsWith:modelArr];
        }
        
    } withFail:^(id result) {
        
    }];
}


//保存数据到NSUserDefaults
- (void)saveNSUserDefaultsWith:(NSMutableArray *)modelArr;
{
     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
     [userDefaults setObject:modelArr forKey:@"allOptions"];
     //这里建议同步存储到磁盘中，但是不是必须的
     [userDefaults synchronize];
}
 //从NSUserDefaults中读取数据
- (id)readNSUserDefaults {
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
        //读取数组NSArray类型的数据
    return [userDefaultes arrayForKey:@"currentArr"];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        self.oldArr = [user arrayForKey:@"allOptions"].mutableCopy;
        if (_oldArr.count == 0) {
            _oldArr = [NSMutableArray arrayWithCapacity:0];
            [user setObject:_oldArr forKey:@"allOptions"];
            [user synchronize];
        }
        [self handleData];
        self.optionsArr = [self readNSUserDefaults];
    }
    return self;
}







#pragma mark - 设置navigationBar属性
- (void)setNavigationBar {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"订阅" style:(UIBarButtonItemStyleDone) target:self action:nil];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"lianxiren"] style:(UIBarButtonItemStyleDone) target:self action:@selector(barButtonItem:)];
    item.tag = 10000;
    item.tintColor = [UIColor whiteColor];
    UIBarButtonItem *item_t = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sousuo"] style:(UIBarButtonItemStyleDone) target:self action:@selector(barButtonItem:)];
    item_t.tag = 10001;
    item_t.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItems = @[item, item_t];
}
- (void)barButtonItem:(UIBarButtonItem *)button {
    if (button.tag == 10000) {
        ZGLmyVC *my = [[ZGLmyVC alloc]init];
        [self.navigationController pushViewController:my animated:YES];
    }
    if (button.tag == 10001) {
        ZGLSearchVC *searchVC = [[ZGLSearchVC alloc] init];
        [self.navigationController pushViewController:searchVC animated:YES];
    }
}

#pragma mark - tableView创建
- (void)createSubscibeTableView {
    self.subscibeTableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:(UITableViewStylePlain)];
    /* 隐藏cell之间的分割线 */
    self.subscibeTableView.separatorStyle = NO;
    self.subscibeTableView.delegate = self;
    self.subscibeTableView.dataSource = self;
    [self.subscibeTableView registerClass:[ZGLShufflingViewCell class] forCellReuseIdentifier:@"ZGLSubscribeVC_ZGLShufflingViewCell"];
    [self.subscibeTableView registerClass:[ZGLSubscribeCell class] forCellReuseIdentifier:@"ZGLSubscribeVC_ZGLSubscribeCell"];
    [self.view addSubview:self.subscibeTableView];
}

- (void)viewWillAppear:(BOOL)animated {
    self.optionsArr = [self readNSUserDefaults];
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.barTintColor = naviColor;
    self.view.backgroundColor = backColor;
    self.subscibeTableView.backgroundColor = backColor;
    [self.subscibeTableView reloadData];
}

#pragma mark - 页面主程序入口
- (void)viewDidLoad {
    NSLog(@"%@",NSHomeDirectory());
    [super viewDidLoad];
    [self setNavigationBar];
    [self createSubscibeTableView];
    [self readNSUserDefaults];
    [self handleData];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (0 == indexPath.row) {
        ZGLShufflingViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZGLSubscribeVC_ZGLShufflingViewCell"];
        return cell;
    } else {
        ZGLSubscribeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZGLSubscribeVC_ZGLSubscribeCell"];
        cell.optionsArr = [NSMutableArray arrayWithArray:self.optionsArr];
        cell.delegate = self;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (0 == indexPath.row) {
        return ScaleY * 200;
    } else {
        return ((self.optionsArr.count + 1) / 3 + 1) * ScaleY * 125;
    }
}

#pragma  - mark 推出详情列表界面
- (void)pushDetailsVCWith:(BOOL)isLast with:(NSDictionary *)dic {
    if (isLast == YES) {
        ZGLSearchVC *searchVC = [[ZGLSearchVC alloc] init];
        [self.navigationController pushViewController:searchVC animated:YES];
    } else {
        NSString *type = dic[@"data_type"];
        if (type.length == 0) {
            ZGLSubDetailsVC *detailsVC = [[ZGLSubDetailsVC alloc] init];
            [self deleteIdsWith:dic with:detailsVC];
            [self.navigationController pushViewController:detailsVC animated:YES];
        }
        if ([type isEqualToString:@"topic"]) {
            ZGLTopicTypeVC *topicVC = [[ZGLTopicTypeVC alloc] init];
            [self handleTopicModelWithDic:dic with:topicVC];
            [self.navigationController pushViewController:topicVC animated:YES];
        }
        if ([type isEqualToString:@"photo_news"]) {
            ZGLTablePicVC *picVC = [[ZGLTablePicVC alloc] init];
            [self handlePicVCModelWithDic:dic with:picVC];
            [self.navigationController pushViewController:picVC animated:YES];
        }
        if ([type isEqualToString:@"rss"]) {
            ZGLSubDetailsVC *detailsVC = [[ZGLSubDetailsVC alloc] init];
            [self deleteIdsWith:dic with:detailsVC];
            [self.navigationController pushViewController:detailsVC animated:YES];
        }
        if ([type isEqualToString:@"photo"]) {
            ZGLPhotoVC *photoVC = [[ZGLPhotoVC alloc] init];
            [self addAllPhotoWith:dic with:photoVC];
            [self.navigationController pushViewController:photoVC animated:YES];
        }
        if ([type isEqualToString:@"episode"]) {
            ZGLEpisodeVC *news = [[ZGLEpisodeVC alloc] init];
            news.title = dic[@"title"];
            [self episodeTypeHandleDataWith:dic with:news];
            [self.navigationController pushViewController:news animated:YES];
        }
    }
}
- (void)episodeTypeHandleDataWith:(NSDictionary *)dic with:(ZGLEpisodeVC *)news {
    [ZGLHTTPTOOL GETWithURL:dic[@"api_url"] withBody:nil withHttpHead:nil responseStyle:JSON withSuccess:^(id result) {
        NSMutableArray *arr = result[@"data"][@"articles"];
        news.viewUrl = result[@"data"][@"ipadconfig"][@"pages"][0][@"diy"][@"bgimage_url"];
        news.nextUrl = result[@"data"][@"info"][@"next_url"];
        NSMutableArray *modelArr = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *dict in arr) {
            ZGLSubDetModel *model = [ZGLSubDetModel modWithDic:dict];
            if (model.auther_name.length > 0) {
                [modelArr addObject:model];
            }
        }
        news.modelArr = modelArr;
    } withFail:^(id result) {
        
    }];
}
- (void)deleteIdsWith:(NSDictionary *)dic with:(ZGLSubDetailsVC *)detailsVC {
    [ZGLHTTPTOOL GETWithURL:dic[@"api_url"] withBody:nil withHttpHead:nil responseStyle:JSON withSuccess:^(id result) {
        detailsVC.yuanDic = dic;
        detailsVC.titleUrl = result[@"data"][@"ipadconfig"][@"pages"][0][@"diy"][@"bgimage_url"];
        NSMutableArray *arr = result[@"data"][@"articles"];
        NSMutableArray *modelArr = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *dict in arr) {
            ZGLSubDetModel *model = [ZGLSubDetModel modWithDic:dict];
            if (model.auther_name.length > 0) {
                [modelArr addObject:model];
            }
        }
        detailsVC.detListArr = modelArr;
    } withFail:^(id result) {
    }];
}

- (void)handleTopicModelWithDic:(NSDictionary *)dic with:(ZGLTopicTypeVC *)topicVC {
    [ZGLHTTPTOOL GETWithURL:dic[@"api_url"] withBody:nil withHttpHead:nil responseStyle:JSON withSuccess:^(id result) {
        topicVC.dateStr = result[@"data"][@"list"][0][@"date"];
        NSMutableArray *arr = result[@"data"][@"list"][0][@"topic_list"];
        NSMutableArray *modelArr = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *dict in arr) {
            ZGLTopicDetModel *model1 = [ZGLTopicDetModel modWithDic:dict];
            [modelArr addObject:model1];
        }
        topicVC.topicModelArr = modelArr;
    } withFail:^(id result) {
        
    }];
}

- (void)handlePicVCModelWithDic:(NSDictionary *)dic with:(ZGLTablePicVC *)tableVC {
    [ZGLHTTPTOOL GETWithURL:dic[@"api_url"] withBody:nil withHttpHead:nil responseStyle:JSON withSuccess:^(id result) {
        
        tableVC.yuanUrlStr = dic[@"api_url"];
        tableVC.urlStr = result[@"data"][@"info"][@"next_url"];
        NSMutableArray *arr = result[@"data"][@"articles"];
        NSMutableArray *modelArr = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *dict in arr) {
            ZGLPicVCModel *model  = [ZGLPicVCModel modWithDic:dict];
            [modelArr addObject:model];
        }
        tableVC.picModelArr = modelArr;
    } withFail:^(id result) {
       
    }];
}
- (void)addAllPhotoWith:(NSDictionary *)dic with:(ZGLPhotoVC *)photoVC {
    [ZGLHTTPTOOL GETWithURL:dic[@"api_url"] withBody:nil withHttpHead:nil responseStyle:JSON withSuccess:^(id result) {
        photoVC.yuanDic = dic;
        photoVC.urlStr = result[@"data"][@"info"][@"next_url"];
        photoVC.yuanUrl = dic[@"api_url"];
        NSMutableArray *arr = result[@"data"][@"articles"];
        NSMutableArray *modelArr = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *dict in arr) {
            ZGLPicVCModel *model  = [ZGLPicVCModel modWithDic:dict];
            [modelArr addObject:model];
        }
        photoVC.photoArr = modelArr;
    } withFail:^(id result) {
        
    }];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
